package com.chenjt.netty.eight_nio.selector.chat;

import io.netty.buffer.ByteBuf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2024/8/23 11:47
 */
public class NioClient {

    public static void main(String[] args) throws Exception{

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_CONNECT);// 客户端向服务器端发起连接
        socketChannel.connect(new InetSocketAddress("127.0.0.1",8899));

        while(true){
            selector.select();
            Set<SelectionKey> keySet = selector.selectedKeys();

            for(SelectionKey selectionKey : keySet){
                if(selectionKey.isConnectable()){
                    SocketChannel client = (SocketChannel)selectionKey.channel();

                    // 是否处于连接过程当中
                    if(client.isConnectionPending()){
                        // 处于连接过程当中就完成连接，表示连接已经真正建立好了
                        client.finishConnect();

                        ByteBuffer writeBuffer = ByteBuffer.allocate(1024);

                        writeBuffer.put((LocalDateTime.now() + " 连接成功").getBytes());
                        writeBuffer.flip();
                        client.write(writeBuffer);

                        ExecutorService executorService = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
                        executorService.submit(()->{
                            while (true){
                                try {
                                    writeBuffer.clear();
                                    InputStreamReader input = new InputStreamReader(System.in);
                                    BufferedReader br = new BufferedReader(input);

                                    String sendMessage = br.readLine();

                                    writeBuffer.put(sendMessage.getBytes());
                                    writeBuffer.flip();
                                    client.write(writeBuffer);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    client.register(selector,SelectionKey.OP_READ);
                }else if(selectionKey.isReadable()){// 有数据可读
                    SocketChannel client = (SocketChannel)selectionKey.channel();

                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);

                    int count = client.read(readBuffer);

                    if(count > 0){
                        String receiveMessage = new String(readBuffer.array(),0,count);
                        System.out.println(receiveMessage);
                    }

                }
            }

            // 清除已经处理完的SelectionKey
            keySet.clear();
        }
    }

}
